package com.bilibili.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.bilibili.dao.BaseDao;
import com.bilibili.dao.DanmakuDao;
import com.bilibili.dto.DanmakuInfo;
import com.bilibili.entity.Danmaku;
import com.bilibili.entity.Page;

public class DanmakuDaoImpl implements DanmakuDao {
	@Override
	public int selectCountByUpId(int upId) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		int total = 0;
		try {
			String sql = "SELECT COUNT(*) AS total FROM danmaku WHERE up_id = ? AND status = 1";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, upId);
			rs = ps.executeQuery();
			if (rs.next()) {
				total = rs.getInt("total");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return total;
	}

	@Override
	public int selectCountByUpIdD(int upId) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		int total = 0;
		try {
			String sql = "SELECT COUNT(*) AS total FROM danmaku WHERE up_id = ? AND status = 0";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, upId);
			rs = ps.executeQuery();
			if (rs.next()) {
				total = rs.getInt("total");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return 0; // 错误时返回0，避免前端显示异常值
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return total;
	}

	@Override
	public List<Danmaku> selectAllByUpId(int upId) {
		Connection conn = BaseDao.getConn();
		String sql = "SELECT * FROM danmaku WHERE up_id = ?";
		List<Danmaku> list = new ArrayList<>();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, upId);
			rs = ps.executeQuery();
			while (rs.next()) {
				Danmaku d = new Danmaku();
				d.setDanmakuId(rs.getLong("danmaku_id"));
				d.setVideoId(rs.getInt("video_id"));
				d.setUserId(rs.getInt("user_id"));
				d.setContent(rs.getString("content"));
				d.setCreateTime(rs.getTimestamp("create_time"));
				d.setPlayTime(rs.getInt("play_time"));
				d.setStatus(rs.getInt("status"));
				d.setUpId(rs.getInt("up_id"));
				list.add(d);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return list;
	}

	@Override
	public Page<Danmaku> selectByUpIdWithPage(int upId, int pageNum, int pageSize) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Danmaku> danmakuList = new ArrayList<>();
		int totalRows = selectTotalRowsByUpId(upId);
		try {
			pageSize = 5; // 固定每页显示5条弹幕
			String sql = "SELECT * FROM danmaku WHERE up_id = ? LIMIT ?, ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, upId);
			ps.setInt(2, (pageNum - 1) * pageSize);
			ps.setInt(3, pageSize);
			rs = ps.executeQuery();
			while (rs.next()) {
				Danmaku d = new Danmaku();
				d.setDanmakuId(rs.getLong("danmaku_id"));
				d.setVideoId(rs.getInt("video_id"));
				d.setUserId(rs.getInt("user_id"));
				d.setContent(rs.getString("content"));
				d.setCreateTime(rs.getTimestamp("create_time"));
				d.setPlayTime(rs.getInt("play_time"));
				d.setStatus(rs.getInt("status"));
				d.setUpId(rs.getInt("up_id"));
				danmakuList.add(d);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return new Page<>(danmakuList, pageNum, pageSize, totalRows);
	}

	@Override
	public int selectTotalRowsByUpId(int upId) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		int totalRows = 0;
		try {
			String sql = "SELECT COUNT(*) AS total FROM danmaku WHERE up_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, upId);
			rs = ps.executeQuery();
			if (rs.next()) {
				totalRows = rs.getInt("total");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return totalRows;
	}

	@Override
	public int updateStatus(int danmakuId, int status) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		int affectedRows = 0;
		try {
			String sql = "UPDATE danmaku SET status = ? WHERE danmaku_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, status);
			ps.setInt(2, danmakuId);
			affectedRows = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, null);
		}
		return affectedRows;
	}

	public Page<Danmaku> selectByUpIdWithPageAndFilters(String sql, Object[] params) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Danmaku> danmakuList = new ArrayList<>();
		int totalRows = 0;

		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			rs = ps.executeQuery();

			// 处理总记录数
			if (sql.toLowerCase().startsWith("select count")) {
				if (rs.next()) {
					totalRows = rs.getInt(1);
				}
			} else {
				// 只查询弹幕数据，不包含视频标题
				while (rs.next()) {
					Danmaku d = new Danmaku();
					d.setDanmakuId(rs.getLong("danmaku_id"));
					d.setVideoId(rs.getInt("video_id"));
					d.setUserId(rs.getInt("user_id"));
					d.setContent(rs.getString("content"));
					d.setCreateTime(rs.getTimestamp("create_time"));
					d.setPlayTime(rs.getInt("play_time"));
					d.setStatus(rs.getInt("status"));
					d.setUpId(rs.getInt("up_id"));
					danmakuList.add(d);
				}
				totalRows = danmakuList.size();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}

		return new Page<>(danmakuList, 1, 10, totalRows);
	}

	@Override
	public int selectTotalRowsByUpIdWithFilters(int upId, String whereClause, Object[] params) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		int totalRows = 0;
		try {
			String sql = "SELECT COUNT(*) AS total FROM danmaku " + whereClause;
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			rs = ps.executeQuery();
			if (rs.next()) {
				totalRows = rs.getInt("total");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return totalRows;
	}

	@Override
	public List<Danmaku> selectDanmakuByVideoId(int videoId) {
		Connection conn = BaseDao.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Danmaku> danmakuList = new ArrayList<>();
		try {
			String sql = "SELECT * FROM danmaku WHERE video_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, videoId);
			rs = ps.executeQuery();
			while (rs.next()) {
				Danmaku d = new Danmaku();
				d.setDanmakuId(rs.getLong("danmaku_id"));
				d.setVideoId(rs.getInt("video_id"));
				d.setUserId(rs.getInt("user_id"));
				d.setContent(rs.getString("content"));
				d.setCreateTime(rs.getTimestamp("create_time"));
				d.setPlayTime(rs.getInt("play_time"));
				d.setStatus(rs.getInt("status"));
				d.setUpId(rs.getInt("up_id"));
				d.setVideoTitle(rs.getString("video_title"));
				danmakuList.add(d);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return danmakuList;
	}

	@Override
	public int selectAllDanmakuNum() {
		// TODO Auto-generated method stub
		Connection conn = BaseDao.getConn();// 打开连接
		String sql = "SELECT count(1) as total FROM danmaku";
		PreparedStatement ps = null;
		ResultSet rs = null;
		int row = 0;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				row = rs.getInt("total");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, ps, rs);
		}
		return row;
	}

	@Override
	public List<DanmakuInfo> selectAllDanmakuB(String content, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		Connection conn=BaseDao.getConn();//打开连接
		List<Object> queryList = new ArrayList<Object>();
		String sql = "SELECT * FROM danmaku WHERE status = 1 ";
		if(content != null && !content.equals("")) {
			sql+="AND content like concat('%',?,'%') ";
			queryList.add(content);
		}
		sql+="LIMIT ?,?";
		List<DanmakuInfo> list = new ArrayList<DanmakuInfo>();
		PreparedStatement ps= null;
		ResultSet rs=null;
		try {
			ps= conn.prepareStatement(sql);
			for(int i = 0;i<queryList.size();i++) {
				ps.setObject(i+1, queryList.get(i));
			}
			ps.setInt(queryList.size()+1, (pageNum-1)*pageSize);
			ps.setInt(queryList.size()+2, pageSize);
			rs = ps.executeQuery();			
			while(rs.next()) {
				 DanmakuInfo danmaku = new DanmakuInfo();
				 danmaku.setDanmakuId(rs.getLong("danmaku_id"));
				 danmaku.setVideoId(rs.getInt("video_id"));
				 danmaku.setUserId(rs.getInt("user_id"));
				 danmaku.setContent(rs.getString("content"));
				 danmaku.setCreateTime(rs.getTimestamp("create_time"));
				 danmaku.setState(rs.getInt("status"));
				 danmaku.setPlayTime(rs.getInt("play_time"));
				 list.add(danmaku);
		    }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(conn, ps,rs);
		}
		return list;
	}
	
	@Override
	public int deleteDanmakuB(int danmakuId) {
		// TODO Auto-generated method stub
		String sql = "update danmaku set status = 0 where danmaku_id = ?";
		Object[] param = { danmakuId };
		return BaseDao.executeUpdate(sql, param);
	}
	@Override
	public int selectAllDanmakuBNum(String content) {
		// TODO Auto-generated method stub
		Connection conn=BaseDao.getConn();//打开连接
		String sql = "SELECT count(1) as total FROM danmaku WHERE status = 1 ";
		List<Object> queryList = new ArrayList<Object>();
		if(content != null && !content.equals("")) {
			sql+="AND content like concat('%',?,'%') ";
			queryList.add(content);
		}
		PreparedStatement ps= null;
		ResultSet rs=null;
		int row = 0;
		try {
			ps= conn.prepareStatement(sql);
			for(int i = 0;i<queryList.size();i++) {
				ps.setObject(i+1, queryList.get(i));
			}
			rs = ps.executeQuery();			
			if(rs.next()) {
			    row = rs.getInt("total");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(conn, ps,rs);
		}
		return row;
	}
}